class Milestone < ActiveRecord::Base
  belongs_to :project
  
  has_many :activities
  has_many :comments, :as => :commentable
  
  validates_presence_of :title, :due
  
  named_scope :with_activities, :joins => "LEFT JOIN activities on activities.milestone_id = milestones.id", 
                                :select => "milestones.*, count(activities.id) as activities_quantity, count(activities.completed_at) as completed",
                                :group => "milestones.id"
  
  named_scope :completed, :joins => :activities, 
                          :select => "milestones.*, count(activities.id) as activities_quantity, count(activities.completed_at) as completed",
                          :group => "milestones.id",
                          :having => "activities_quantity = completed"

  named_scope :pending,   :joins => :activities, 
                          :select => "milestones.*, count(activities.id) as activities_quantity, count(activities.completed_at) as completed",
                          :group => "milestones.id",
                          :having => "activities_quantity > completed"
                          
  named_scope :late,      :joins => :activities, 
                          :select => "milestones.*, count(activities.id) as activities_quantity, count(activities.completed_at) as completed",
                          :group => "milestones.id",
                          :conditions => ["milestones.due < ?", Date.current],
                          :having => "activities_quantity > completed"
  
  def to_param
    "#{id}#{title.gsub(/[^a-z0-9]+/i, '-')}".downcase
  end
  
  def late?
    Date.current > due
  end
  
  
  has_many :logs, :as => :loggable
  
  after_create :log_creation
  after_update :log_update
  after_destroy :log_delete
  
  def log_creation
    logs.new(:project => project, :action => "created", :user_id => Thread.current[:user_id]).save
  end
  
  def log_update
    logs.new(:project => project, :action => "changed", :user_id => Thread.current[:user_id]).save
  end
  
  def log_delete
    logs.new(:project => project, :action => "deleted", :user_id => Thread.current[:user_id]).save
  end

end
